//
//  LGMeViewController.m
//  LoverGo
//
//  Created by YeXiao on 14-1-14.
//  Copyright (c) 2014年 yexiao. All rights reserved.
//

#import "LGUtil.h"
#import "UMFeedback.h"
#import "LGSignInView.h"
#import "LGUserInfo.h"
#import "Photo.h"
#import "Toast+UIView.h"
#import "LGRequestManager.h"
#import "LGDataCenter.h"
#import "LGLoginViewController.h"
#import "LGMeViewController.h"
#import "LGRequestManager.h"
#import "EMAsyncImageView.h"
#import "AboutViewController.h"
#import "LGInfoItemViewController.h"
#import "LGSettingItemController.h"
#import "ALLOrderViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>

#define ORIGINAL_MAX_WIDTH 640.0f

@interface LGMeViewController ()

@end

@implementation LGMeViewController

-(id)initWithTitle:(NSString *)title image:(UIImage *)img type:(MainViewType)mvtype
{
    self = [super init];
    if (self) {
        self.tabBarItem = [[UITabBarItem alloc] initWithTitle:title image:img tag:mvtype];
    }
    return self;
}

-(void)loadView
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginNof:) name:loginSPath object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginNof:) name:registerSPath object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginNof:) name:userUpDateSPath object:nil];
    
    if (([LGDataCenter getSingleton].userInfo == nil)) {
        //弹出注册登录界面
        LGSignInView* signInView = [[LGSignInView alloc] initWithFrame:CGRectMake(0, STATUSBAR, SCREEN_WIDTH, SCREEN_HEIGHT)];
        signInView.delegate = self;
        [self setView:signInView];
    }else{
        _meView = [[LGMeView alloc] initWithFrame:CGRectMake(0, STATUSBAR, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _meView.delegate = self;
        _meView.meTView.dataSource = self;
        _meView.meTView.delegate = self;
        [self setView:_meView];
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
}
-(void)viewDidUnload
{
    [[NSNotificationCenter defaultCenter] removeObserver:loginSPath name:nil object:self];
    [[NSNotificationCenter defaultCenter] removeObserver:registerSPath name:nil object:self];
    [[NSNotificationCenter defaultCenter] removeObserver:userUpDateSPath name:nil object:self];
}
-(void)loginNof:(NSNotification *)nof
{
    if ([[nof name] compare:loginSPath] == 0        ||
        [[nof name] compare:registerSPath] == 0     ||
        [[nof name] compare:userUpDateSPath] == 0
        ) {
        [self loadView];
    }
}

-(void)LGMeViewSignOut
{
    self.actionSheet = [[LXActionSheet alloc]initWithTitle:@"退出后不会删除任何历史数据,下次登录依然可以使用本账号" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"退出登录" otherButtonTitles:nil];
    [self.actionSheet showInView:self.view];
    
}
#pragma mark - LXActionSheetDelegate

- (void)didClickOnButtonIndex:(NSInteger *)buttonIndex
{
    if (self.actionSheet.tag == 2) {
        if ((int)buttonIndex == 1) {
            // 从相册中选取
            if ([self isPhotoLibraryAvailable]) {
                UIImagePickerController *controller = [[UIImagePickerController alloc] init];
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
                [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
                controller.mediaTypes = mediaTypes;
                controller.delegate = self;
                [self presentViewController:controller
                                   animated:YES
                                 completion:^(void){
                                     NSLog(@"Picker View Controller is presented");
                                 }];
            }
        }
    }
}

- (void)didClickOnDestructiveButton
{
    if (self.actionSheet.tag == 1) {
        [[LGDataCenter getSingleton] signOut];
        [self loadView];
    }else if (self.actionSheet.tag == 2){
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}
#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    _itemIView.image = editedImage;
    NSString *imageString=[Photo image2String:editedImage];
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        //上传图片
        NSMutableDictionary *para = [[NSMutableDictionary alloc] init];
        [para setObject:[LGDataCenter getSingleton].userInfo.uuid forKey:@"appUser.uuid"];
        [para setObject:imageString forKey:@"photo"];
        [[LGRequestManager getSingleton] sendRequestAboutUser:userUpDateSPath para:para];
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

-(void)LGSignInViewBtnClieck:(LGSignInType)type
{
    switch (type) {
        case LGSignInTypeBtnRegrister:
        {
            break;
        }
        case LGSignInTypeLogin:
        {
            LGLoginViewController *vc = [[LGLoginViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case LGSignInTypeSys:
        {
            break;
        }
        case LGSignInTypeHelp:
        {
            [UMFeedback showFeedback:self withAppkey:UmengAppkey];
            break;
        }
        case LGSignInTypeAbout:
        {
            AboutViewController *vc = [[AboutViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case LGSignInTypeMe:
        {
            LGSettingItemController *vc = [[LGSettingItemController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        default:
            break;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 100;
    }
    if (indexPath.row == 6) {
        return 150;
    }
    return 40;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    static NSString * showUserInfoCellIdentifier = @"CityTableViewCell";
    UITableViewCell * cell = [[UITableViewCell alloc] init];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    
    [cell.textLabel setText:[NSString stringWithFormat:@"%d",indexPath.row]];
    if (indexPath.row == 0) {
        //头像
        UIImageView *meIV= [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cover_requests_avatar.png"]];
        [meIV setFrame:CGRectMake(10, 15, 70, 70)];
        meIV.userInteractionEnabled = YES;
        [cell addSubview:meIV];
        
        UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeHeadImg:)];
        [meIV addGestureRecognizer:tgr];
        
        _itemIView = [[EMAsyncImageView alloc] initWithFrame:CGRectMake(3, 3, 64, 64) cornerRadius:4];
        [meIV addSubview:_itemIView];
        _itemIView.userInteractionEnabled = YES;
        LGUserInfo* info =[LGDataCenter getSingleton].userInfo;
        if (info == NULL) {
            return cell;
        }
        if ([info.headImg compare:@""] == 0)
        {
            _itemIView.image = [LGUtil getUnFoundImage];
        }else{
            _itemIView.imageUrl = [NSString stringWithFormat:@"%@lover-go/%@",baseUrl,info.headImg];
        }
        UILabel* nameLab = [[UILabel alloc]initWithFrame:CGRectMake(90, 40, 230, 20)];
        [nameLab setBackgroundColor:[UIColor whiteColor]];
        [nameLab setShadowColor:[UIColor whiteColor]];
        [nameLab setShadowOffset:CGSizeMake(0.1, 0.1)];
        UIFont *font = [UIFont fontWithName:@"Helvetica" size:18];
        [nameLab setFont:font];
        [nameLab setTextColor:[UIColor blackColor]];
        [nameLab setTextAlignment:NSTextAlignmentLeft];
        if ([info.userName compare:@""] == 0) {
            [nameLab setText:info.mobile];
        }else{
            [nameLab setText:info.userName];
        }
        [cell addSubview:nameLab];
        
    }
    if (indexPath.row == 1){
        [cell.textLabel setText:@"个人信息"];
    }
    if (indexPath.row == 2){
        [cell.textLabel setText:@"订单详情"];
    }
    if (indexPath.row == 3){
        [cell.textLabel setText:@"清理缓存"];
    }
    if (indexPath.row == 4){
        [cell.textLabel setText:@"帮助与反馈"];
    }
    if (indexPath.row == 5){
        [cell.textLabel setText:@"关于去哪儿"];
    }
    if (indexPath.row == 6) {
        UIButton *signOutBtn =[LGUtil get9ScalBtn:CGRectMake(10, 53, 300, 44) type:TypeColorGreen];
        [signOutBtn setTitle:@"注销" forState:UIControlStateNormal];
        [signOutBtn addTarget:self action:@selector(signOutBtnClieck) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:signOutBtn];
        UILabel* notLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 320, 20)];
        [notLab setBackgroundColor:[UIColor clearColor]];
        UIFont *font = [UIFont fontWithName:@"Helvetica" size:14];
        [notLab setFont:font];
        [notLab setTextColor:[UIColor blackColor]];
        [notLab setTextAlignment:NSTextAlignmentCenter];
        [notLab setText:@"情侣去哪儿,发现生活中的浪漫"];
        [cell addSubview:notLab];
    }
    if (indexPath.row > 0&& indexPath.row < 6) {
        UIImageView *imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"next_pic.png"]];
        [imgView setCenter:CGPointMake(290, STATUSBAR)];
        [cell addSubview:imgView];
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1) {
        LGSettingItemController *vc = [[LGSettingItemController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.row == 2) {
        ALLOrderViewController *vc = [[ALLOrderViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.row ==3) {
        [LGUtil cleanCache];
        [self.view makeToast:@"清理缓存成功" duration:3.0 position:@"center"];
    }
    if (indexPath.row ==4) {
        [UMFeedback showFeedback:self withAppkey:UmengAppkey];
    }
    if (indexPath.row ==5) {
        AboutViewController *vc = [[AboutViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(void)signOutBtnClieck
{
    self.actionSheet = [[LXActionSheet alloc]initWithTitle:@"退出后不会删除任何历史数据,下次登录依然可以使用本账号" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"退出登录" otherButtonTitles:nil];
    self.actionSheet.tag = 1;
    [self.actionSheet showInView:self.view];
}
-(void)changeHeadImg:(id)sender
{
    self.actionSheet = [[LXActionSheet alloc]initWithTitle:@"上传头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@[@"从相册中选取"]];
    self.actionSheet.tag = 2;
    [self.actionSheet showInView:self.view];
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
